﻿#include <QPainter>

#include "xvideo.h"
#include "ffmpeg.h"
#include "xaudio.h"
#include "xplay.h"

namespace HeaderMedia {

XVideo::XVideo() : xTimeId(0) {
  qDebug() << "XVideo";
}

XVideo::~XVideo() {
  stop();
}

void XVideo::start(QString fileName) {
  fileName.replace("file:///", "");
  FFmpeg::getInstance().open(fileName);

  // 播放总时间
  int sec = FFmpeg::getInstance().totalMs() / 1000; // 秒
  int min = sec / 60; // 分
  int remainSec = sec - min * 60;
  xTotalTime = QString::number(min) + ":" + QString::number(remainSec);
  emit totalTimeChanged(xTotalTime);

  XAudio::getInstance().setSampleRate(FFmpeg::getInstance().sampleRate());
  XAudio::getInstance().setSampleSize(FFmpeg::getInstance().sampleSize());
  XAudio::getInstance().setChannel(FFmpeg::getInstance().channel());
  // 播放音频
  XAudio::getInstance().start();
  FFmpeg::getInstance().setPlayStatus(true);

  // 刷新频率
  startTimer(20);
  XPlay::getInstance().myStart();
}

void XVideo::stop() {
  if (xTimeId != 0) {
    killTimer(xTimeId);
  }

  XPlay::getInstance().myStop();
  XAudio::getInstance().stop();
}

void XVideo::pause() {
  FFmpeg::getInstance().setPlayStatus(false);
}

void XVideo::volume(qreal value) {
  XAudio::getInstance().volume(value);
}

void XVideo::paint(QPainter *pPainter) {
  static QImage *image = nullptr;

  // 记录之前的窗口大小
  static int w = 0;
  static int h = 0;
  if (w != width() || h != height()) {
    // 如果窗口大小发生变化，删除内存
    if (image) {
      delete image->bits();
      delete image;
      image = nullptr;
    }
  }

  if (image == nullptr) {
    uchar *buffer = new uchar[width() * height() * 4];
    image = new QImage(buffer, width(), height(), QImage::Format_ARGB32);
  }

  FFmpeg::getInstance().yuvToRGB((char *)(image->bits()), width(), height());
  pPainter->drawImage(QPoint(0, 0), *image);
}

void XVideo::timerEvent(QTimerEvent *e) {
  xTimeId = e->timerId();
  this->update();

  int currentMin = (FFmpeg::getInstance().pts() / 1000) / 60;
  int currentSec = (FFmpeg::getInstance().pts() / 1000) % 60;
  xCurrentTime = QString::number(currentMin) + ":" + QString::number(currentSec);
  emit currentTimeChanged(xCurrentTime);
}

QString XVideo::currentTime() const {
  return xCurrentTime;
}

QString XVideo::totalTime() const {
  return xTotalTime;
}

} // namespace HeaderMedia













